package net.codeyouth.codegen.util

import net.codeyouth.codegen.bean.Config

import java.sql.Connection
import java.sql.DriverManager
import java.sql.Types

/**
 * @author Frank create on 16/2/20 21:53
 */
class DBUtil {

    final static ThreadLocal<Connection> CONN_HOLDER = new ThreadLocal<>()

    /**
     * 获取数据库连接.
     *
     * @return Connection
     */
    static Connection getConnection() {
        Connection conn = CONN_HOLDER.get()
        if (conn == null) {
            Class.forName(Config.JDBC_DRIVER)
            conn = DriverManager.getConnection(Config.JDBC_URL, Config.JDBC_USER, Config.JDBC_PASSWORD)
            CONN_HOLDER.set(conn)
        }
        return conn
    }

    /**
     * 数据库数据类型转换为 Java 数据类型.
     *
     * @param databaseType 数据库数据类型
     * @return
     */
    public static String toJavaType(String databaseType) {
        String javaType = ""


        switch (databaseType) {
            case "FLOAT":
                javaType = "float"
                break
            case "DOUBLE":
                javaType = "double"
                break
            case "DECIMAL":
                javaType = "java.math.BigDecimal"
                break
            case "BIT":
                javaType = "boolean"
                break
            case "ID":
            case "INTEGER":
            case "TIMESTAMP":
                javaType = "long"
                break
            case "INT":
            case "SMALLINT":
            case "TINYINT":
            case "BOOLEAN":
                javaType = "int"
                break
            case Types.BIGINT:
                javaType = "java.math.BigInteger"
                break
            case "VARCHAR":
            case "NVARCHAR":
            case "LONGVARCHAR":
            case "LONGNVARCHAR":
            case "LONGVARBINARY":
            case "CHAR":
            case "NCHAR":
            case "TEXT":
                javaType = "String"
                break
            case "BLOB":
                javaType = "byte[]"
                break
            case "DATE":
            case "DATETIME":
                javaType = "java.util.Date"
                break
            default:
                System.out.println("找不到数据类型:" + databaseType)
                break
        }
        return javaType
    }

}
